package com.example.project44

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
class MainActivity : ComponentActivity() {

    private var name = "张三"
    private var gender = "男"
    private var phone = "13800138000"
    private var highScore = 0

    private lateinit var tvName: TextView
    private lateinit var tvGender: TextView
    private lateinit var tvPhone: TextView
    private lateinit var tvHighScore: TextView
    private lateinit var btnEdit: Button
    private lateinit var btnPlay: Button

    private val editInfoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val data = result.data
            name = data?.getStringExtra("name") ?: "未知"
            gender = data?.getStringExtra("gender") ?: "未知"
            phone = data?.getStringExtra("phone") ?: "未设置"
            updatePlayerInfo()
        }
    }
    private val gameScoreLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val newScore = result.data?.getIntExtra("score", 0) ?: 0
            if (highScore == 0 || newScore < highScore) {
                highScore = newScore
                updatePlayerInfo()
            }
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViews()
        updatePlayerInfo()
        setListeners()
    }
    private fun initViews() {
        tvName = findViewById(R.id.tv_name)
        tvGender = findViewById(R.id.tv_gender)
        tvPhone = findViewById(R.id.tv_phone)
        tvHighScore = findViewById(R.id.tv_high_score)
        btnEdit = findViewById(R.id.btn_edit)
        btnPlay = findViewById(R.id.btn_play)
    }

    private fun setListeners() {
        btnEdit.setOnClickListener { goToEditActivity() }
        btnPlay.setOnClickListener { goToGameActivity() }
    }

    private fun updatePlayerInfo() {
        tvName.text = "姓名：$name"
        tvGender.text = "性别：$gender"
        tvPhone.text = "电话：$phone"
        tvHighScore.text = "当前最高分：$highScore"
    }

    private fun goToEditActivity() {
        val intent = Intent(this, EditInfoActivity::class.java).apply {
            putExtra("name", name)
            putExtra("gender", gender)
            putExtra("phone", phone)
        }
        editInfoLauncher.launch(intent)
    }

    private fun goToGameActivity() {
        val intent = Intent(this, GameActivity::class.java)
        gameScoreLauncher.launch(intent)
    }
}